package com.asurplus;

import com.asurplus.google.GoogleAuthenticator;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目启动类
 *
 * @author Asurplus
 */
@RestController
@SpringBootApplication
public class AsurplusApplication {

    private static String SECRET_KEY = "";

    public static void main(String[] args) {
        SpringApplication.run(AsurplusApplication.class, args);
    }

    /**
     * 生成 Google 密钥，两种方式任选一种
     */
    @GetMapping("getSecretKey")
    public String getSecretKey() {
        String secretKey = GoogleAuthenticator.getSecretKey();
        SECRET_KEY = secretKey;
        return secretKey;
    }

    /**
     * 生成二维码，APP直接扫描绑定，两种方式任选一种
     */
    @GetMapping("getQrcode")
    public void getQrcode(@RequestParam("name") String name, HttpServletResponse response) throws Exception {
        String secretKey = GoogleAuthenticator.getSecretKey();
        SECRET_KEY = secretKey;
        // 生成二维码内容
        String qrCodeText = GoogleAuthenticator.getQrCodeText(secretKey, name, "");
        // 生成二维码输出
        new SimpleQrcodeGenerator().generate(qrCodeText).toStream(response.getOutputStream());
    }

    /**
     * 获取code
     */
    @GetMapping("getCode")
    public String getCode() {
        return GoogleAuthenticator.getCode(SECRET_KEY);
    }

    /**
     * 验证 code 是否正确
     */
    @GetMapping("checkCode")
    public Boolean checkCode(@RequestParam("code") String code) {
        return GoogleAuthenticator.checkCode(SECRET_KEY, Long.parseLong(code), System.currentTimeMillis());
    }
}
